﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;
using Models;

namespace DAL
{
    /// <summary>
    /// 销售员数据访问类
    /// </summary>
   public class SalesPersonService
    {

        /// <summary>
        /// 根据登录账号和密码实现用户登录
        /// </summary>
        /// <param name="objPerson">包含登录账号和密码的用户对象</param>
        /// <returns>返回包含登录账号、密码和用户名的对象或null</returns>
        public SalesPerson UserLogin(SalesPerson objPerson)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select SPName from SalesPerson where SalesPersonId=@SalesPersonId");
            sb.Append(" and LoginPwd=@LoginPwd");
            SqlParameter[] param = new SqlParameter[]
            {
                new SqlParameter("@SalesPersonId", objPerson.SalePersonId),
                new SqlParameter("@LoginPwd", objPerson.LoginPwd)
            };

            object result = SQLHelper.GetSingleResult(sb.ToString(), param);
            if(result == null)  //如果用户名或密码错误则直接返回null
            {
                return null;
            }
            else
            {
                objPerson.SPName = result.ToString();  //封装对象
                return objPerson;
            }

        }

        /// <summary>
        /// 添加登录日志，返回日志编号
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public int WriteLoginLog(LoginLog info)
        {
            string sql = "insert into LoginLogs (LoginId, SPName, ServerName)";
            sql += " values (@LoginId, @SPName, @ServerName);select @@identity";

            SqlParameter[] param = new SqlParameter[]
            {
                new SqlParameter("@LoginId", info.LoginId),
                new SqlParameter("@SPName", info.SPName),
                new SqlParameter("@ServerName", info.ServerName)
            };
            return Convert.ToInt32(SQLHelper.GetSingleResult(sql, param));
        }

        public int WriteExitLog(int logId, DateTime dateTime)
        {
            string sql = "update LoginLogs set ExitTime=@ExitTime where LogId=@LogId";
            SqlParameter[] param = new SqlParameter[]
            {
                new SqlParameter("@ExitTime", dateTime),
                new SqlParameter("@LogId", logId)
            };
            return SQLHelper.Update(sql, param);
        }

       
        public DateTime getDBServerTime()
        {
            return SQLHelper.GetDBServerTime();
        }





    }
}
